import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, ajax, promptBox,toast,deepClone, getMultiLang } from 'nc-lightapp-front';
import './index.less';
import ReferLoader from '../../../public/ReferLoader/index.js';
import { onButtonClick, initTemplate } from '../syncTree/events';
import HeaderArea from '../../../public/components/HeaderArea';
import SyncTree from '../chooseModal';
class SelfExecute extends Component {
	constructor(props) {
		super(props);
		this.state = {
			accountingbook: {
				refname: '',
				refpk: ''
			},
			tableData: [],
			pk_unitState: false,
			pk_unit: {
				refname: '',
				refpk: ''
			},
			beforChangeData: [],
			json: {}
		};
	}
	//获取默认账簿
	queryAppcontext = () => {
		let url = '/nccloud/platform/appregister/queryappcontext.do';
		let data = {
			appcode: this.props.getSearchParam('c')
		};
		ajax({
			url,
			data,
			success: (response) => {
				const { data, error, success } = response;
				if (success && data) {
					// if (!data.defaultAccbookPk) {
					// 	return;
					// }
					let accountingbook = {
						refname: data.defaultAccbookName,
						refpk: data.defaultAccbookPk
					};
					this.props.getPK(accountingbook.refpk);
					this.setState({
						accountingbook
					}, ()=>{
						if(data.defaultAccbookPk){
							let url = '/nccloud/gl/voucher/queryTransProject.do';
							let localdata = {
								pk_accountingbook: accountingbook.refpk
							};
							ajax({
								url,
								data: localdata,
								success: (response) => {
									const { data, error, success } = response;
									if (success && data) {
										data.push({});
										this.setState({
											transArr: data
										});
									} else {
									}
								}
							});
						}
					});
					
				} else {
				}
			}
		});
	}
	componentWillMount() {
		let callback= (json) =>{
			this.setState({
				json:json,
			},()=>{		  
				initTemplate.call(this, this.props);
				//获取默认账簿
				this.queryAppcontext()
			})
		}
		getMultiLang({moduleId:'20020SDTPEPAGE',domainName:'gl',currentLocale:'simpchn',callback});
		
		this.props.button.setButtonVisible([ 'select_transdef', 'save', 'cancel' ], false);
		this.props.button.setButtonDisabled([ 'update', 'delete' ], true);
	}
	updateButtonStatus(disabled){
		this.props.button.setButtonDisabled(['delete' ], disabled);
	}
	setButtonDisabled = (disabled) => {
		this.props.button.setButtonDisabled([ 'update', 'delete' ], disabled);
	}
	componentWillUpdate(nextProps,nextState){
		if(!this.props.selectedValue && nextProps.selectedValue){
			this.props.button.setButtonDisabled([ 'update' ], false);
		}
	}
	componentWillReceiveProps(nextProps) {
		let tableData = nextProps.tableData;
		this.setState({
			tableData
		});
	}
	componentDidMount(){
		this.props.SelfExecuteRef(this);
	}
	handChangeNum = () => {
		let { tableData } = this.state;
		let beforChangeData = deepClone(tableData)
		for (let i = 0, len = tableData.length; i < len; i++) {
			tableData[i].isEdit = true;
		}
		this.props.getEditTableData(tableData);
		this.setState({
			beforChangeData
		})
	};
	//修改
	handleRepair = () => {
		let {accountingbook} = this.state
		let { selectedValue } = this.props;
		if(!accountingbook.refpk){
			toast({ content: this.state.json['20020SDTPEPAGE-000007'] , color: 'warning' })/* 国际化处理： 请先选择财务核算账簿！*/
			return 
		}	
		if(!selectedValue){
			toast({ content: this.state.json['20020SDTPEPAGE-000008'] , color: 'warning' })/* 国际化处理： 请先选择方案节点！*/
			return 
		}
		this.handChangeNum()
		this.props.button.setButtonVisible([ 'update', 'delete' ], false);
		this.props.button.setButtonVisible([ 'select_transdef', 'save', 'cancel' ], true);	
	};

	//取消
	handleCancel = () => {
		let {beforChangeData} = this.state
		promptBox({
			color: 'warning',
			title: this.state.json['20020SDTPEPAGE-000002'],  /* 国际化处理： 取消*/
			content: this.state.json['20020SDTPEPAGE-000009'],/* 国际化处理： 确定要取消吗？*/
			beSureBtnClick: () => {
				this.setState({
					tableData: beforChangeData
				},()=>{
					this.props.getEditTableData(this.state.tableData);
				})
				this.props.button.setButtonVisible([ 'update', 'delete' ], true);
				this.props.button.setButtonVisible([ 'select_transdef', 'save', 'cancel' ], false);
			},
			cancelBtnClick: () => {}
		});

	};

	handleDel = () => {
		//删除
		let checkData = this.props.getCheckedData();
		if (checkData.length > 0) {
			promptBox({
				color: 'warning',
				title: this.state.json['20020SDTPEPAGE-000010'],  /* 国际化处理： 删除*/
				content: this.state.json['20020SDTPEPAGE-000011'],/* 国际化处理： 确定要删除吗？*/
				beSureBtnClick: () => {
					this.beSureDel(checkData);
				},
				cancelBtnClick: () => {
					// this.refresh();
				}
			});
		} else {
			toast({ content: this.state.json['20020SDTPEPAGE-000012'], color: 'warning' });/* 国际化处理： 请选择要删除的结转定义！*/
		}
	};
	beSureDel = (checkData) => {
		let url = '/nccloud/gl/voucher/deleteTransProjDef.do';
		let { tableData } = this.state;
		let data = [];
		checkData.map((item) => {
			let obj = {};
			obj.pk_transproj = item.pk_transproj;
			obj.pk_accountingbook = item.pk_accountingbook;
			obj.pk_transfer = item.pk_transfer;
			data.push(obj);
		});
		let self = this;
		ajax({
			url,
			data,
			success: function(response) {
				const { data, error, success } = response;
				if (success) {
					if (data) {
						let successArr = [];
						let errArr = [];
						let successPktransferArr = [];
						let errPktransferArr = [];
						data.map((item) => {
							if (item.result === 'Y') {
								successArr.push(item);
								successPktransferArr.push(item.pk_transfer);
							} else {
								errArr.push(item);
								errPktransferArr.push(item.pk_transfer);
							}
						});
						if (errArr.length > 0) {
							let errmsg = errPktransferArr.toString();
							toast({ content: `${self.state.json['20020SDTPEPAGE-000016']}：${errmsg}`, color: 'danger' });/* 国际化处理： 你无权限删除以下结转定义*/
						}
						if (errArr.length === 0 && successArr.length > 0) {
							toast({ content: self.state.json['20020SDTPEPAGE-000013'], color: 'success' });/* 国际化处理： 删除成功*/
						}
						let newTableData = tableData.filter((item) => {
							return successPktransferArr.indexOf(item.pk_transfer) == '-1';
						});
						self.props.getEditTableData(newTableData);
					}
				} else {
				}
			}
		});
	};

	handleSave = () => {
		//保存
		let { selectedValue } = this.props;
		let url = '/nccloud/gl/voucher/updateTransProjDefExno.do';
		let { tableData } = this.state;
		for (let i = 0, len = tableData.length; i < len; i++) {
			delete tableData[i].key;
			tableData[i].exeno = String(tableData[i].exeno);
		}
		let exenoArr = tableData.map(item => item.exeno)
		if(exenoArr.includes("")){
			toast({ content: this.state.json['20020SDTPEPAGE-000014'] , color: 'warning' })/* 国际化处理： 结转序号不能为空*/
		} else {
			let self = this;
			ajax({
				url,
				data: tableData,
				success: function(response) {
					const { data, error, success } = response;
					if (success) {
						self.props.onSelectEve(selectedValue);
						toast({ content: self.state.json['20020SDTPEPAGE-000015'], color: 'success' });/* 国际化处理： 保存成功*/
						self.props.button.setButtonVisible([ 'update', 'delete' ], true);
						self.props.button.setButtonVisible([ 'select_transdef', 'save', 'cancel' ], false);
					} else {
					}
				}
			});
		}
		
	};
	handChoose = () => {
		//弹框
		this.props.modal.show('choose')
	};
	handleConfirm = () => { //data
		let data = this.SyncTree.getCheckedData();
		let { tableData } = this.props;
		let tempArr = tableData;
		for (let i = 0, len = data.length; i < len; i++) {
			var repeat = false;
			for (let j = 0, len = tableData.length; j < len; j++) {
				if (data[i].pk_transfer === tableData[j].pk_transfer) {
					repeat = true;
					break;
				}
			}
			if (!repeat) {
				tempArr.push(data[i]);
			}
		}
		this.props.getSelectDetails(tempArr);
		this.props.modal.close('choose')
	};
	renderReferLoader() {
		let { accountingbook } = this.state;
		let accbookRefCode = 'uapbd/refer/org/AccountBookTreeRef/index.js';
		return (
			<ReferLoader
				tag="accountingbook"
				fieldid='accountingbook'
				refcode={accbookRefCode}
				isMultiSelectedEnabled={false}
				showGroup={false}
				showInCludeChildren={false}
				disabledDataShow={true}
				value={{ refname: accountingbook.refname, refpk: accountingbook.refpk }}
				queryCondition={() => {
					let condition = {
						TreeRefActionExt: 'nccloud.web.gl.ref.AccountBookRefSqlBuilder',
						appcode: ''
					};
					condition.appcode = this.props.getSearchParam('c');
					return condition;
				}}
				onChange={(v) => {
					this.props.getPK(v.refpk);
					this.setState({
						accountingbook: v
					});
					this.props.onAccountingbookSelect(v.refpk);
				}}
			/>
		);
	}
	modalContent = () => {
		let { accountingbook, tableData } = this.state;
		let { appcode, pagecode } = this.props;
		return(
			<SyncTree
				pk_accountingbook={accountingbook.refpk}
				orgTableData={tableData}
				appcode = {appcode}
				pagecode = {pagecode}
				SyncTreeRef={(init) => {this.SyncTree = init}}
			/>
		)
	}
	render() {
		let { modal} = this.props;
		let { createModal } = modal;
		return [
			<HeaderArea 
				title = {this.props.getSearchParam('n')}
				searchContent = {<div className="main-org">{this.renderReferLoader()}</div>}
				btnContent = {this.props.button.createButtonApp({
					area: 'page_header',
					onButtonClick: onButtonClick.bind(this),
					popContainer: document.querySelector('.btn-group')
				})}
			/>,
			<div>
				{createModal('choose', {
					title: this.state.json['20020SDTPEPAGE-000000'], /* 国际化处理： 选择转账定义*/
					size:'xlg', //  模态框大小 sm/lg/xlg
					content: this.modalContent(), //弹框内容，可以是字符串或dom
					beSureBtnClick: this.handleConfirm,//点击确定按钮事件
				})}
			</div>,
		];
	}
}

SelfExecute = createPage({})(SelfExecute);
export default SelfExecute;
// ReactDOM.render(<SelfExecute />, document.querySelector('#app'));
